package com.zjw.zy

import android.content.*
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.IBinder
import android.view.Menu
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.core.view.doOnLayout
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.Navigation
import com.zjw.zy.aidl.binder.IAppServiceBinder
import com.zjw.zy.base.BaseActivity
import com.zjw.zy.base.special.ActiveTaskPool
import com.zjw.zy.bean.UIMode
import com.zjw.zy.constant.AppConstant
import com.zjw.zy.constant.AppUIColorStyle
import com.zjw.zy.constant.NotificationArgsKey
import com.zjw.zy.coreui.view.FootBarView
import com.zjw.zy.coreui.view.NaviSlideView
import com.zjw.zy.coreui.view.TopBarView
import com.zjw.zy.manager.PageManager
import com.zjw.zy.smi.JustWithIt2
import com.zjw.zy.utils.*
import com.zjw.zy.viewmodel.AppViewModel
import com.zjw.zy.viewmodel.SettingViewModel
import com.zjw.zy.viewmodel.WsMessageDispatchViewModel
import ocr.ocr.ui.service.OrcRecognizeService


/**
 * @author ：zhong.jw
 * @date ：Created in 2022/9/26 9:02
 */
class MainActivity : BaseActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    private val mAppViewModel: AppViewModel by viewModels()
    private val mWsMessageDispatchViewModel: WsMessageDispatchViewModel by viewModels()
    private val settingViewModel: SettingViewModel by viewModels()

    private val mResumeTask = ActiveTaskPool()
    private val mServiceConnectTask = ActiveTaskPool()
    private val mResultTask = HashMap<Int, JustWithIt2<Int, Intent?>>()
    private var mAppService: IAppServiceBinder? = null
    private val mTopBarView: TopBarView by lazy { findViewById(R.id.topbar) }
    private val mLeftSlide: NaviSlideView by lazy { findViewById(R.id.app_left_slide) }
    private val mAppContent: DrawerLayout by lazy { findViewById(R.id.app_content) }
    private val mFootBarView: FootBarView by lazy { findViewById(R.id.footbar) }
    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mAppService = IAppServiceBinder.Stub.asInterface(service)

            mServiceConnectTask.active()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            mAppService = null
            mServiceConnectTask.unActive()
            //启动service
            bindService(
                Intent().apply {
                    action = AppService.SERVICE_ACTION
                    `package` = packageName
                },
                this,
                BIND_AUTO_CREATE
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AppUtils.addMain(this)
        PageManager.init(this)
        WindowUtils.init(this)
        PathUtils.init(this)
        NotificationUtils.initChannel(this)
        immersive()
        bindService(
            Intent().apply {
                action = AppService.SERVICE_ACTION
                `package` = packageName
            },
            mServiceConnection,
            BIND_AUTO_CREATE
        )
        mServiceConnectTask.post {
            mAppViewModel.requestUIMode()
            //注册connect消息分发
            mWsMessageDispatchViewModel.init()
        }
    }

    override fun onPause() {
        super.onPause()
        TimeUtils.stop(this)
    }

    override fun onResume() {
        super.onResume()

        TimeUtils.start(this)
        mResumeTask.doIgnoreActive()

        onSubscribe()

    }

    private fun onSubscribe() {
        mAppViewModel.getAppUIMode().observe(this) {
            setUIMode(it)
        }

        settingViewModel.getStartUpImage().observe(this) {
            it?.let {
                mLeftSlide.setImage(
                    BitmapDrawable(
                        resources,
                        PathUtils.getBitmapFromPath(it.value)
                    )
                )
            }
        }
    }

    override fun onNewIntent(intent: Intent?) {
        LogUtils.d(TAG, "onNewIntent")
        //如果有通知，就进入通知对应页面
        intent?.getBundleExtra(NotificationUtils.BUNDLE_KEY)
            ?.getInt(NotificationArgsKey.TARGET_FRAGMENT)
            ?.let { res ->
                mResumeTask.post {
                    navigationController().let { nav ->
                        nav.popBackStack()
                        nav.navigate(res)
                    }
                }
            }
        super.onNewIntent(intent)
    }


    override fun onDestroy() {
        AppUtils.removeMain()
        unbindService(mServiceConnection)
        mWsMessageDispatchViewModel.unInit()
        super.onDestroy()
    }

    override fun onBindListener() {
        mTopBarView.bindListener(object : TopBarView.TopBarListener {
            override fun onBackClick() {
                LogUtils.d(TAG, "onBackClick")
                PageManager.getTopFragment()?.onBackClick()
            }

            override fun onNavClick() {
                LogUtils.d(TAG, "onNavClick")
                mAppContent.openDrawer(GravityCompat.START)
            }
        })


        mFootBarView.bindListener(object : FootBarView.FootBarListener {
            override fun onClickFootBarItem(item: String) {
                when (item) {
                    FootBarView.NAV_1 -> {
                        //主页
                        PageManager.goMain()
                    }
                    FootBarView.NAV_2 -> {
                        //备忘录
                        PageManager.goMemorandum()
                    }
                    FootBarView.NAV_3 -> {
                        //聊天
                        PageManager.goWechat()
                    }
                    FootBarView.NAV_4 -> {
                        PageManager.goToolsNav()
                    }
                }
            }
        })

        mLeftSlide.bindListener(object : NaviSlideView.OnListener {
            override fun onCallLove() {
                mAppContent.closeDrawer(GravityCompat.START, true)
                PhoneUtils.call(AppConstant.LOVE_BOY_PHONE)
            }

            override fun onCallSetting() {
                mAppContent.closeDrawer(GravityCompat.START, true)
                navigationController().navigate(R.id.nav_setting_fragment)
            }

            override fun onCallTips() {
                mAppContent.closeDrawer(GravityCompat.START, true)
                navigationController().navigate(R.id.nav_tips_fragment)
            }

            override fun onCallCalendar() {
                mAppContent.closeDrawer(GravityCompat.START, true)
                PageManager.goCalendar()
            }

            override fun onAccessClick() {
                mAppContent.closeDrawer(GravityCompat.START, true)
                PageManager.goAccess()
            }
        })
    }

    override fun onBindValue() {

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.toolbar, menu)
        return true
    }

    override fun onFindView() {
    }

    override fun onLayoutId(): Int {
        return R.layout.main_activity
    }

    override fun onBackPressed() {
        LogUtils.d(TAG, "onBackPressed")
        PageManager.getTopFragment()?.onBackClick()
    }

    fun navigationController() = Navigation.findNavController(this, R.id.nav_host_main)

    fun topBar(): TopBarView = mTopBarView
    fun footBar(): FootBarView = mFootBarView

    fun service(): IAppServiceBinder? = mAppService

    fun observerActivityResult(requestCode: Int, call: JustWithIt2<Int, Intent?>) {
        mResultTask[requestCode] = call
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (OrcRecognizeService.processActivityResult(requestCode, resultCode, data)) {
            return
        }
        mResultTask.remove(requestCode)?.onWith(resultCode, data)
    }

    override fun finish() {
        moveTaskToBack(false)
    }

    private fun setUIMode(mode: UIMode) {
        if (mode.colorStyle == AppUIColorStyle.GRAY_MODE) {
            Paint().apply {
                colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
                    setSaturation(0f)
                })
                window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, this)
            }
        }

        if (mode.colorStyle == AppUIColorStyle.NORMAL_MODE) {
            Paint().apply {
                colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
                    setSaturation(1f)
                })
                window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, this)
            }
        }
    }
}